<?php

/**
 * This is the model class for table "Comment".
 *
 * The followings are the available columns in table 'Comment':
 * @property string $id
 * @property string $alias
 * @property string $body
 * @property integer $ups
 * @property integer $downs
 * @property integer $edited
 * @property string $status
 * @property string $entryId
 * @property string $creatorId
 * @property string $created
 * @property string $updated
 * @property integer $deleted
 *
 * The followings are the available relations in the table 'Comment':
 * @property User $author
 * @property Entry $entry
 * @property Comment $parent
 */
class Comment extends CActiveRecord
{
	const STATUS_HIDDEN = 0;
	const STATUS_NORMAL = 1;
	const STATUS_REPORTED = 2;

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className the class name
	 * @return Comment the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'Comment';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		return array(
			array('alias, body, status, entryId', 'required'),
			array('edited, deleted', 'numerical', 'integerOnly'=>true),
			array('alias', 'length', 'max'=>255),
			array('status, entryId, creatorId', 'length', 'max'=>10),
			array('ups, downs, edited, status, creatorId, created, updated', 'safe'),
			array('id, alias, body, edited, status, entryId, creatorId, created, updated', 'safe', 'on'=>'search'),
			array('body','filter','filter'=>array($obj=new CHtmlPurifier(),'purify')),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		return array(
			'author' => array(self::BELONGS_TO, 'User', 'creatorId'),
			'entry' => array(self::BELONGS_TO, 'Entry', 'entryId'),
		);
	}

	/**
	 * @return array attached behaviors.
	 */
	public function behaviors()
	{
		return array(
			'ext.auditbehavior.AuditBehavior',
			'ext.deletedbehavior.DeletedBehavior',
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => Yii::t('label', 'Id'),
			'alias' => Yii::t('label', 'Alias'),
			'body' => Yii::t('label', 'Body'),
			'ups' => Yii::t('label', 'Ups'),
			'downs' => Yii::t('label', 'Downs'),
			'edited' => Yii::t('label', 'Edited'),
			'status' => Yii::t('label', 'Status'),
			'entryId' => Yii::t('label', 'Entry'),
			'creatorId' => Yii::t('label', 'Author'),
			'created' => Yii::t('label', 'Created'),
			'updated' => Yii::t('label', 'Updated'),
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		$criteria = new CDbCriteria;

		$criteria->with[] = 'entry';
		$criteria->with[] = 'author';

		$criteria->compare('t.id',$this->id,true);
		$criteria->compare('t.alias',$this->alias,true);
		$criteria->compare('t.body',$this->body,true);
		$criteria->compare('t.edited',$this->edited,true);
		$criteria->compare('t.status',$this->status,true);
		$criteria->compare('entry.name',$this->entryId,true);
		$criteria->compare('author.name',$this->creatorId,true);
		$criteria->compare('t.created',$this->created,true);
		$criteria->compare('t.updated',$this->updated,true);

		$criteria->addCondition('t.deleted=0');

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Rates this comment either up or down.
	 * @param integer $userId the user id.
	 * @param integer $type the rate type.
	 * @return boolean
	 */
	public function rate($userId, $type)
	{
		$rate = Rate::model()->findByAttributes(array(
			'raterId'=>$userId,
			'commentId'=>$this->id,
		));

		if ($rate === null)
		{
			$rate = new Rate();
			$rate->raterId = $userId;
			$rate->commentId = $this->id;
			$rate->type = $type;
			$rate->save(false);

			if ($type == Rate::TYPE_UP)
				$this->ups++;
			else
				$this->downs++;

			$this->save(false);
			return true;
		}
		else
			return false;
	}

	/**
	 * Returns whether a specific user has rated this comment.
	 * @param $userId the user id.
	 * @return boolean
	 */
	public function hasRated($userId)
	{
		$rate = Rate::model()->findByAttributes(array(
			'raterId'=>$userId,
			'commentId'=>$this->id,
		));

		return $rate !== null;
	}

	/**
	 * @return string the URL to this comment.
	 */
	public function getUrl()
	{
		return Yii::app()->createUrl('entry/view', array('id'=>$this->entryId, '#'=>'comment-'.$this->id));
	}

	/**
	 * @return string the "created ago" string for this comment.
	 */
	public function getCreatedAgoString()
	{
		$string = '';

		$command = Yii::app()->db->createCommand('SELECT NOW() AS now');
		$result = $command->query();
		$nowDate = $result->readColumn(0);

		$now = strtotime($nowDate);
		$created = strtotime($this->created);
		$seconds = $now - $created;

		$minutes = round($seconds / 60);

		// Minutes
		if ($minutes < 60)
		{
			if ($minutes <= 1)
				$string = Yii::t('frontend', '1 minute ago');
			else
				$string = Yii::t('frontend', ':amount minutes ago', array(':amount'=>$minutes));
		}
		// Hours
		else if ($minutes >= 60 && $minutes < 1440)
		{
			$hours = round($minutes / 60);

			if ($hours <= 1)
				$string = Yii::t('frontend', '1 hour ago');
			else
				$string = Yii::t('frontend', ':amount hours ago', array(':amount'=>$hours));
		}
		// Days
		else if ($minutes >= 1440 && $minutes < 43200)
		{
			$days = round($minutes / 60 / 24);

			if ($days <= 1)
				$string = Yii::t('frontend', '1 day ago');
			else
				$string = Yii::t('frontend', ':amount days ago', array(':amount'=>$days));
		}
		// Months
		else if ($minutes >= 43200 && $minutes < 518400)
		{
			$months = round($minutes / 60 / 24 / 30);

			if ($months <= 1)
				$string = Yii::t('frontend', '1 month ago');
			else
				$string = Yii::t('frontend', ':amount months ago', array(':amount'=>$months));
		}
		// Years
		else
		{
			$years = round($minutes / 60 / 24 / 30 / 12);

			if ($years === 1)
				$string = Yii::t('frontend', '1 year ago');
			else
				$string = Yii::t('frontend', ':amount years ago', array(':amount'=>$years));
		}

		return $string;
	}

	public function getStatusString()
	{
		$options = self::getStatusOptions();
		return isset($options[$this->status]) ? $options[$this->status] : Yii::t('admin','Unknown');
	}

	public static function getStatusOptions()
	{
		return array(
			self::STATUS_HIDDEN => Yii::t('admin','Hidden'),
			self::STATUS_NORMAL => Yii::t('admin','Normal'),
			self::STATUS_REPORTED => Yii::t('admin','Reported'),
		);
	}
}